package com.visionork.android.twe.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.visionork.android.twe.parser.VarietyShowScheduleAdapterImpl;

public class ShowScheduleActivity extends ListActivity {
	public static final String SCHEDULE_TITLE = "SCHEDULE_TITLE";
	public static final String SCHEDULE_URL = "SCHEDULE_URL";
	private String _schedule_url;
	private String _schedule_title;

	private class LoadScheduleTask extends AsyncTask<Void, Void, Void> {
		private ProgressDialog _pd;
		@Override
		protected Void doInBackground(Void... params) {
			try {
				_schedule_list = (new VarietyShowScheduleAdapterImpl(_schedule_url))
						.get_schedule();
			} catch (Throwable e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPreExecute() {
			_pd = ProgressDialog.show(ShowScheduleActivity.this, "加载中...",
					"读取节目列表", true, false);
		}

		@Override
		protected void onPostExecute(Void param) {
			List<String> titles = new ArrayList<String>();
			for (ShowSchedule schedule : _schedule_list) {
				titles.add(schedule.get_title());
			}

			setListAdapter(new ArrayAdapter<String>(ShowScheduleActivity.this,
					R.layout.show_schedule_list_item, titles));
			
			_pd.dismiss();
		}
	}

	/** Called when the activity is first created. */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.show_schedule_list);
		_schedule_url = getIntent().getStringExtra(SCHEDULE_URL);
		_schedule_title = getIntent().getStringExtra(SCHEDULE_TITLE);
		TextView tv = (TextView) findViewById(R.id.show_schedule_title);
		tv.setText(_schedule_title);
		load_schedule();
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		ShowSchedule schedule = _schedule_list.get(position);
		Intent intent = new Intent(this, EpisodeActivity.class);
		intent.putExtra(EpisodeActivity.EPISODE_TITLE, schedule.get_title());
		intent.putExtra(EpisodeActivity.EPISODE_URL, schedule.get_url());
		startActivity(intent);
	}
	
	private void load_schedule() {
		LoadScheduleTask task = new LoadScheduleTask();
		task.execute(new Void[] {});
	}

	private ArrayList<ShowSchedule> _schedule_list;
}
